package com.tanhua.sso.service.impl;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.tanhua.sso.config.AliyunSMSConfig;
import com.tanhua.sso.service.SmsService;
import com.tanhua.sso.vo.ErrorResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;

@Service
@Slf4j
public class SmsServiceImpl implements SmsService {
    @Autowired
    private AliyunSMSConfig aliyunSMSConfig;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    /**
     * 发送短信验证
     * @param mobile  电话号码
     * @return 成功返回验证码,失败返回null
     */
    @Override
    public String sendSms(String mobile) {
        DefaultProfile profile = DefaultProfile.getProfile(this.aliyunSMSConfig.getRegionId(),
                this.aliyunSMSConfig.getAccessKeyId(), this.aliyunSMSConfig.getAccessKeySecret());
        IAcsClient client = new DefaultAcsClient(profile);
        //随机生成6位验证码
        String code= RandomUtils.nextInt(100000,999999)+"";
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain(this.aliyunSMSConfig.getDomain());
        request.setSysVersion("2021-08-05");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", this.aliyunSMSConfig.getRegionId());
        request.putQueryParameter("PhoneNumbers", mobile); //目标手机号
        request.putQueryParameter("SignName", this.aliyunSMSConfig.getSignName()); //签名名称
        request.putQueryParameter("TemplateCode", this.aliyunSMSConfig.getTemplateCode()); //短信模板code
        request.putQueryParameter("TemplateParam", "{\"code\":\""+code+"\"}");//模板中变量替换
        try {
            CommonResponse response = client.getCommonResponse(request);
            //查看是否包含ok
            String data=response.getData();
            if(StringUtils.contains(data,"\"Message\":\"OK\"")){
                return code;
            }
            log.info("发送短信成功~~data="+data);
            //{"Message":"OK","RequestId":"EC2D4C9A-0EAC-4213-BE45-CE6176E1DF23","BizId":"110903802851113360^0","Code":"OK"}
           // System.out.println(response.getData());
        } catch (Exception e) {
            log.error("发送短信失败~~mobile="+mobile,e);
        }
        return null;
    }
    /**
     * 发送短信验证码
     * 实现:发送成功后将验证码保存到redis中
     * @param phone 电话号码
     * @return
     */
    @Override
    public ErrorResult sendCheckCode(String phone) {
        String key="CHECK_CODE_"+phone;
//        System.out.println("验证码.");
        //判断验证码是否失效
        if (this.redisTemplate.hasKey(key)) {
            //上次发送的验证码未失效!!!
            String msg="上次发送的验证码未失效!!!";
            return ErrorResult.builder().errCode("000001").errMessage(msg).build();
        }
//        String code = this.sendSms(phone);
        String code="123456";
        if (StringUtils.isEmpty(code)) {
            String msg="发送短信验证码失败!!";
            return ErrorResult.builder().errCode("000000").errMessage(msg).build();
        }
        this.redisTemplate.opsForValue().set(key,code, Duration.ofMinutes(5));
        return null;
    }
}
